const mongoose = require('mongoose')
const db = 'mongodb://localhost/simle-db'
const glob = require('glob')
const {
  resolve
} = require('path')
// 引入Schemas静态文件
exports.initSchemas = () => {
  glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}
mongoose.Promise = global.Promise
exports.connect = () => {
  // 连接数据库
  mongoose.connect(db, {
    useNewUrlParser: true
  })
  let maxConnetTimes = 0
  return new Promise((resolve, reject) => {
    // 把所有连接放到这里
    // 增加数据库连接的事件监听
    mongoose.connection.on('disconnected', (err) => {
      // 进行重连
      if (maxConnetTimes <= 3) {
        maxConnetTimes++
        mongoose.connect(db)
      } else {
        reject(err)
        throw new Error('数据库出现问题，程序无法处理请人为修理。。。。。。。')
      }
    })
    // 数据库出现错误的时候
    mongoose.connection.on('error', (err) => {
      if (maxConnetTimes <= 3) {
        maxConnetTimes++
        mongoose.connect(db)
      } else {
        reject(err)
        throw new Error('数据库出现问题，程序无法处理请人为修理。。。。。。。')
      }
    })
    // 链接打开的时候
    mongoose.connection.once('open', () => {
      console.log('MongoDB数据库连接成功')
      resolve()
    })
  })
}
